package com.lagou.wwyan.rpc.client;

import com.lagou.wwyan.rpc.bean.RpcRequestMonitor;
import com.lagou.wwyan.rpc.bean.RpcRequest;
import com.lagou.wwyan.rpc.bean.RpcResponse;
import com.lagou.wwyan.rpc.handler.RPCClientHandler;
import com.lagou.wwyan.rpc.sirealizer.JSONSerializer;
import com.lagou.wwyan.rpc.sirealizer.RpcDecoder;
import com.lagou.wwyan.rpc.sirealizer.RpcEncoder;
import com.lagou.wwyan.rpc.sirealizer.Serializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.Closeable;
import java.io.IOException;
import java.util.Objects;

public class RpcClient implements Closeable {
    private RPCClientHandler handler;
    private EventLoopGroup group;
    private Channel channel;
    private Serializer serializer;

    private String host;
    private int port;

    public RpcClient(String host, int port) {
        this.host = host;
        this.port = port;
        this.handler = new RPCClientHandler();
        this.serializer = new JSONSerializer();
    }

    public void initClient() throws InterruptedException {

        //创建连接池对象
        group = new NioEventLoopGroup();
        //创建客户端启动器
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                //这里是序列化
                pipeline.addLast(new RpcEncoder(RpcRequest.class, serializer))
                        .addLast(new RpcDecoder(RpcResponse.class,serializer))
                        .addLast(handler);
            }

        });
        ChannelFuture connect = bootstrap.connect(host, port);
        connect.sync();
        channel = connect.channel();

    }

    /**
     * 关闭客户端
     * @throws IOException
     */
    @Override
    public void close() throws IOException {
        if (channel != null && channel.isActive()){
            channel.close();
        }

        if (group != null && !group.isShutdown()){
            group.shutdownGracefully();
        }
        System.out.println("RpcClient close !");
    }


    public Object send(RpcRequest rpcRequest) throws Exception {
        System.out.println("向"+host +":"+port+"发送请求");
        RpcRequestMonitor.start(rpcRequest.getRequestId(),host,port);
//        return this.channel.writeAndFlush(rpcRequest).sync().get();
        RpcResponse response = handler.sendRequest(rpcRequest);
        RpcRequestMonitor.end(rpcRequest.getRequestId());
        return response;
    }
    /**
     * 判断连接是否有效
     *
     * @return
     */
    public boolean isActive() {
        if (this.channel != null) {
            return this.channel.isActive();
        }
        return false;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        RpcClient rpcClient = (RpcClient) o;
        return port == rpcClient.port &&
                host.equals(rpcClient.host);
    }

    @Override
    public int hashCode() {
        return Objects.hash(host, port);
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }
}
